﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;

namespace SecurityApi.Business
{
    public class PasswordHelper
    {
        private const int PASSWORD_SIZE = 14;
        private const int MinRequiredNonAlphanumericCharacters = 2;


        public PasswordHelper()
        {
        }

        /// <summary>
        /// You can use GenerateSalt() to generate salt
        /// 
        /// Uses SHA1 algorithm
        /// 
        /// </summary>
        /// <param name="passwordFormat"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public string EncodePassword(string inputTextPassword,string salt)
        {
            if ( string.IsNullOrEmpty(salt))
            {
                throw new ApplicationException("Check your user's password information in database.");
            }
            byte[] bIn = Encoding.Unicode.GetBytes(inputTextPassword);
            byte[] bSalt = Convert.FromBase64String(salt);
            byte[] bAll = new byte[bSalt.Length + bIn.Length];
            byte[] bRet = null;

            Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
            Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
            HashAlgorithm s = HashAlgorithm.Create("SHA1");
            bRet = s.ComputeHash(bAll);

            return Convert.ToBase64String(bRet);
        }


        public string GenerateSalt()
        {
            byte[] buf = new byte[16];
            RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
            provider.GetBytes(buf);
            return Convert.ToBase64String(buf);
        }

        /// <summary>
        /// Whenever you want to generate a temporary password, you can use this.
        /// </summary>
        /// <returns></returns>
        public string GeneratePassword()
        {
            return Membership.GeneratePassword(PASSWORD_SIZE, MinRequiredNonAlphanumericCharacters);
        }

    }
}
